#!/usr/bin/python

import sys, os, time, pdb
from daemon import restart_log, run_parser
import MySQLdb
from os.path import isfile, getsize
from pdb import set_trace

#SQL paraneters:
HOST = "localhost"
USER = "root"
PASSWORD = ""
DB = "FW"
#DB = "fw"
#PASSWORD = "ubuntu"


# Test files
LOGFILE = "kern.log"
CFGFILE = "logger.cfg"


#########################
# Prints test results
#
def results(succ, fails):
    print "-------------------------------------------"
    print "%s tests were tested" % (succ + fails)
    print "%s test(s) succeed" %succ
    print "%s test(s) failed" %fails
    print "-------------------------------------------"


#######################
# Test manager.
#
def testSQL():
    fails = 0
    succ = 0
    all = 5
    print "Testing SQL API....\n"
    
    msg = "Start connection"
    cursor, conn = start_connection()
    if cursor and conn:
        succ = succ + 1
        print "%s succeed" %msg
    else:
        fails = fails + 1
        print "%s failed" %msg
        results(succ, all - succ)
        return 

    
    msg = "Crating table"
    if create_table(cursor) == 0:
        print "%s succeed" %msg
        succ = succ + 1
    else:
        print "%s failed" %msg
        results(succ, all - succ)
        return 

   
    msg = "Filling table"
    if fill_table(cursor) == 0:
        succ = succ + 1
        print "%s succeed" %msg
    else:
        fails = fails + 1
        print "%s failed" %msg
        results(succ, all - succ)
        return 

  
    msg = "Printing table"
    if print_table(cursor) == 0:
        succ = succ + 1
        print "%s succeed" %msg
    else:
        fails = fails + 1
        print "%s failed" %msg
        results(succ, all - succ)
        return 


    msg = "End connection"
    if end_connecion(cursor, conn) == 0:
        succ = succ + 1
        print "%s succeed" %msg
    else:
        fails = fails + 1
        print "%s failed" %msg
        results(succ, all - succ)
        return 

    results(succ, fails)


#####################################
# Open session with SQL server
# Output: SQL session
#         SQL connection
def start_connection():
    try:
        print "Trying to establish SQL connection:"
        print "Trying to connect to:"  
        print " host = %s\n user = %s\n passwd = %s\n db = %s" % (HOST, USER, PASSWORD, DB)
        conn = MySQLdb.connect (host = HOST, user = USER, passwd = PASSWORD, db = DB)
        cursor = conn.cursor()
    except MySQLdb.Error, e:
        print "Error %d: %s" % (e.args[0], e.args[1])
        return (None, None)
    
    return (cursor, conn)

###################################
# Closes session with SQL server.
# Input: SQL session
#        SQL connection
#
def end_connecion(cursor, conn):
    try:
        print "Ending connection"
        cursor.close()
        conn.close()
    except MySQLdb.Error, e:
        print "Error %d: %s" % (e.args[0], e.args[1])
        return 1
    
    return 0
 
####################################
# Creates a table in SQL DB.
# Input: SQL session
def create_table(cursor):
    try:
        print "Drop table: test_log"
        cursor.execute ("DROP TABLE IF EXISTS test_log")
        
        print "Create table: test_log"
        cursor.execute ("""
        CREATE TABLE test_log
        (
            time            CHAR(40),
            direct          CHAR(40),
            sourceIP        CHAR(40),
            destIP          CHAR(40),
            sourcePort      CHAR(40),
            destPort        CHAR(40),
            protocol        CHAR(40),
            rulePort        CHAR(40),
            ruleProtocol    CHAR(40),
            action          CHAR(40)
        )
        """)
    except MySQLdb.Error, e:
        print "Error %d: %s" % (e.args[0], e.args[1])
        return 1
    
    return 0

########################################
# Fills an existing table in the SQL DB.
# Input: SQL session
#
def fill_table(cursor):
    try:
        print "Fill table: test_log"
        cursor.execute ("""
        INSERT INTO test_log (time, direct, sourceIP, destIP, sourcePort, destPort, protocol, rulePort, ruleProtocol, action)
        VALUES ('2007-01-16','Out','1.1.1.1','2.2.2.2','1','2','my_protocol','3','my_protocol','Deny')
        """)
    except MySQLdb.Error, e:
        print "Error %d: %s" % (e.args[0], e.args[1])
        return 1

    return 0

##################################################
# Prints the table as it was saved in the SQL DB.
# Input: SQL session
#
def print_table(cursor):
    try:
        print "Printing table: test_log"
        # perform a fetch loop using fetchall()
        cursor.execute ("SELECT * FROM test_log")
        rows = cursor.fetchall ()
        for row in rows:
            print "time = %s" %row[0]
            print "direction = %s" %row[1]
            print "srcIP = %s" %row[2]
            print "dstIP = %s" %row[3]
            print "protocol = %s" %row[4]
            print "srcPort = %s" %row[5]
            print "dstPort = %s" %row[6]
            print "rulePort = %s" %row[7]
            print "ruleProtocol = %s" %row[8]
            print "action = %s" %row[9]
            print "-------------------------------------------"
            print "Number of rows returned: %d" % cursor.rowcount

    except MySQLdb.Error, e:
        print "Error %d: %s" % (e.args[0], e.args[1])
        return 1
        
    return 0

###########################################################################################
# This test reads first 5 OSLFW lines from kern.log, which after restart the
# test parser. Therefore you should verify that there aren't lines which was duplicated.
#
def test_parser():
    print "Testing log parser..."
    print "___________________________________________"
    test = 0
    iter = 0
    fin = open(LOGFILE,"r")
    for i in range(2):
       # restart only for the second iteration
        if i == 1:
            print "restarting..."
            print "-------------------------------------------"
            restart_log(fin)

        while fin.tell() < getsize(fin.name):
            iter = iter + 1
            res = run_parser(fin)
            if res:
                _time         = res[0]
                _direction    = res[1]
                _srcIP        = res[2]
                _dstIP        = res[3]
                _srcPort      = res[4]
                _dstPort      = res[5]
                _protocol     = res[6]
                _rulePort     = res[7]
                _ruleProtocol = res[8]
                _action       = res[9]
 
                print "time = %s" %_time
                print "direction = %s" %_direction
                print "srcIP = %s" %_srcIP
                print "dstIP = %s" %_dstIP
                print "protocol = %s" %_protocol
                print "srcPort = %s" %_srcPort
                print "dstPort = %s" %_dstPort
                print "rulePort = %s" %_rulePort
                print "ruleProtocol = %s" %_ruleProtocol
                print "action = %s" %_action
                print "-------------------------------------------"
                
                # restart after 5 lines
                test = test + 1
                if test == 5:
                    break

    results(iter, 2634 - iter)


###################################
#
# The main function
#
if __name__ == "__main__":
    testSQL()
    test_parser()
    

